package com.example.jk.middlewares;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;

import com.example.jk.core.Context;
import com.example.jk.core.Log;
import com.example.jk.core.Middleware;
import com.example.jk.core.Next;

import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

public class StaticResourceMiddleware implements Middleware {

	public String basePath = "/your/static/resources/path";

	public StaticResourceMiddleware() {

	}

	public StaticResourceMiddleware(String basePath) {
		this.basePath = basePath;

	}

	@Override
	public void handle(Context context,Next next) {
		HttpServerExchange exchange = ((HttpServerContext) context).exchange;
		String path = exchange.getRequestPath();
		File file = new File(basePath + path);

		if (!(isFileNameEnding( path))) {
			//终止handler
			Log.info("!isFileName",basePath + path);
			next.handle(context);
			return;
		}

		if (file.exists() && file.isFile()) {
			try {
//            	 FileUtils.readFile(file.toURL());
				sendFile(exchange, file);
//				next.handle(context);
				
			} catch (IOException e) {
				exchange.setStatusCode(500);
			}
		} else {
			Log.info("file not exists {}", path);
             exchange.setStatusCode(404);
		}

//		HttpServerExchange exchange = ((HttpServerContext) context).exchange;
//		String path = exchange.getRequestPath();
//		File file = new File(basePath + path);
//		if (file.exists() && file.isFile()) {
//			FileUtils.sendFile(exchange, file);
//		} else {
//			exchange.setStatusCode(404);
//		}
		
//		next.handle(context);

	}

	public static void main(String[] args) {
		System.out.println(isFileName("/user"));
		System.out.println(isFileName("/a.ico"));
		
		
		String input = "/user";
        System.out.println(isFileNameEnding(input));
	}
	 public static boolean isFileName(String str) {
	        // 文件名可以包含字母、数字、下划线、点和一些常见的文件扩展名
	        String regex = "\\.[a-zA-Z0-9]+$";
	        Pattern pattern = Pattern.compile(regex);
	        Matcher matcher = pattern.matcher(str);
	        return matcher.matches();
	    }
	 public static boolean isFileNameEnding(String str) {
	        String regex = "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$";
	        Pattern pattern = Pattern.compile(regex);
	        Matcher matcher = pattern.matcher(str);
	        return matcher.find();
	    }

	 
	 
	private void sendFile(HttpServerExchange exchange, File file) throws IOException {
		String mimeType = guessMimeType(file.getName());
		exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, mimeType);

		try (InputStream inputStream = new FileInputStream(file)) {
			IOUtils.copy(inputStream, exchange.getOutputStream());
		}
	}

	private String guessMimeType(String fileName) {
		// 简单的根据文件扩展名猜测 MIME 类型
		if (fileName.endsWith(".html")) {
			return "text/html";
		} else if (fileName.endsWith(".css")) {
			return "text/css";
		} else if (fileName.endsWith(".js")) {
			return "application/javascript";
		} else if (fileName.endsWith(".png")) {
			return "image/png";
		} else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
			return "image/jpeg";
		} else {
			return "application/octet-stream";
		}
	}

}